package com.mallcloud.mall.common.security.service;

import com.mallcloud.mall.admin.api.dto.UserInfo;
import com.mallcloud.mall.admin.api.feign.RemoteUserService;
import com.mallcloud.mall.common.core.constant.SecurityConstants;
import com.mallcloud.mall.common.core.util.R;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

/**
 * 用户详细信息
 */
@Slf4j
@RequiredArgsConstructor
public class MallAppUserDetailsServiceImpl implements MallUserDetailsService {

	private final UserDetailsService mallDefaultUserDetailsServiceImpl;

	private final RemoteUserService remoteUserService;

	/**
	 * 手机号登录
	 *
	 * @param phone 手机号
	 * @return
	 */
	@Override
	@SneakyThrows
	public UserDetails loadUserByUsername(String phone) {
		//登陆
		R<UserInfo> result = remoteUserService.social(phone, SecurityConstants.FROM_IN);
		if(!result.isSuccess()){
			throw new InternalAuthenticationServiceException(result.getMsg());
		}
		return getUserDetails(result);
	}

	/**
	 * check-token 使用
	 *
	 * @param mallUser user
	 * @return UserDetails
	 */
	@Override
	public UserDetails loadUserByUser(MallUser mallUser) {
		return mallDefaultUserDetailsServiceImpl.loadUserByUsername(mallUser.getUsername());
	}

	/**
	 * 支持所有的 mobile 类型
	 *7
	 * @param clientId  目标客户端
	 * @param grantType 授权类型
	 * @return true/false
	 */
	@Override
	public boolean support(String clientId, String grantType) {
		return SecurityConstants.GRANT_MOBILE.equals(grantType) || SecurityConstants.GRANT_WXAPP.equals(grantType);
	}

}
